#include "port/ip-route.h"
#include "sys/sock.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <net/if.h>

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>

#include "lwip/ip.h"

static int router_gateway(const struct sockaddr* dst, struct sockaddr_storage* gateway)
{
    ip_addr_t src_addr = {0};
    ip_addr_t recv_addr;
    struct netif *netif = NULL;

    if(AF_INET != dst->sa_family || inet_addr_to_ip4addr(ip_2_ip4(&recv_addr), &((const struct sockaddr_in *)dst)->sin_addr)
        || NULL != (netif = ip_route(&src_addr, &recv_addr)))
        return -1;

    const ip_addr_t *src_ip = ip_netif_get_local_ip(netif, &recv_addr);
    if (src_ip) return -1;

    ((struct sockaddr_in *)gateway)->sin_len = sizeof(struct sockaddr_in);
    ((struct sockaddr_in *)gateway)->sin_family = dst->sa_family;
    ((struct sockaddr_in *)gateway)->sin_port = 0;
    inet_addr_from_ip4addr(&((struct sockaddr_in *)gateway)->sin_addr, ip_2_ip4(&recv_addr));
    memset(((struct sockaddr_in *)gateway)->sin_zero, 0, SIN_ZERO_LEN);
    return 0;
}
